<template>
  <div class="user-titles-manager">
    <h3>称号管理</h3>
    
    <!-- 当前称号显示 -->
    <div class="current-title-section" v-if="currentTitle">
      <h4>当前称号</h4>
      <div class="current-title-display">
        <span class="title-badge current">{{ currentTitle }}</span>
        <span class="title-description">当前使用的称号</span>
      </div>
    </div>
    
    <!-- 所有可用称号 -->
    <div class="all-titles-section">
      <h4>所有可用称号 ({{ allTitles.length }})</h4>
      
      <div v-if="loading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </div>
      
      <div v-else-if="error" class="error">
        {{ error }}
      </div>
      
      <div v-else class="titles-grid">
        <div 
          v-for="title in allTitles" 
          :key="title.id || title.title"
          class="title-card"
          :class="{ 
            'unlocked': isTitleUnlocked(title),
            'locked': !isTitleUnlocked(title),
            'current': title.title === currentTitle
          }"
        >
          <div class="title-header">
            <span class="title-name">{{ title.title }}</span>
            <div class="title-status">
              <span v-if="title.title === currentTitle" class="status-badge current">当前</span>
              <span v-else-if="isTitleUnlocked(title)" class="status-badge unlocked">已解锁</span>
              <span v-else class="status-badge locked">未解锁</span>
            </div>
          </div>
          
          <div class="title-info">
            <p v-if="title.description" class="title-description">{{ title.description }}</p>
            <p v-if="title.requirement" class="title-requirement">
              解锁条件: {{ title.requirement }}
            </p>
            <p v-if="title.level" class="title-level">
              需要等级: LV.{{ title.level }}
            </p>
          </div>
          
          <div class="title-actions">
            <el-button 
              v-if="isTitleUnlocked(title) && title.title !== currentTitle"
              size="small" 
              type="primary"
              @click="changeTitle(title.title)"
              :loading="changingTitle === title.title"
            >
              使用此称号
            </el-button>
            <el-button 
              v-else-if="!isTitleUnlocked(title)"
              size="small" 
              type="info"
              disabled
            >
              未解锁
            </el-button>
            <el-button 
              v-else
              size="small" 
              type="success"
              disabled
            >
              正在使用
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 称号统计 -->
    <div class="titles-stats" v-if="allTitles.length > 0">
      <div class="stat-item">
        <span class="stat-label">总称号数:</span>
        <span class="stat-value">{{ allTitles.length }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">已解锁:</span>
        <span class="stat-value unlocked">{{ unlockedCount }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">未解锁:</span>
        <span class="stat-value locked">{{ lockedCount }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">解锁进度:</span>
        <span class="stat-value">{{ unlockProgress }}%</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { userLevelAPI } from '@/api'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

const props = defineProps({
  userId: {
    type: String,
    required: true
  }
})

const userStore = useUserStore()

const allTitles = ref([])
const userTitles = ref([])
const currentTitle = ref('')
const loading = ref(false)
const error = ref('')
const changingTitle = ref('')

// 计算属性
const unlockedCount = computed(() => {
  return allTitles.value.filter(title => isTitleUnlocked(title)).length
})

const lockedCount = computed(() => {
  return allTitles.value.length - unlockedCount.value
})

const unlockProgress = computed(() => {
  if (allTitles.value.length === 0) return 0
  return Math.round((unlockedCount.value / allTitles.value.length) * 100)
})

// 检查称号是否已解锁
const isTitleUnlocked = (title) => {
  if (!userTitles.value || userTitles.value.length === 0) return false
  
  // 检查用户是否拥有此称号
  return userTitles.value.some(userTitle => 
    userTitle.title === title.title || userTitle.id === title.id
  )
}

// 加载所有可用称号
const loadAllTitles = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const result = await userLevelAPI.getAllTitles()
    allTitles.value = Array.isArray(result) ? result : []
    
  } catch (err) {
    console.error('加载所有称号失败:', err)
    error.value = '加载称号列表失败'
  } finally {
    loading.value = false
  }
}

// 加载用户称号
const loadUserTitles = async () => {
  try {
    const result = await userLevelAPI.getUserTitles(props.userId)
    userTitles.value = Array.isArray(result) ? result : []
    
    // 获取当前使用的称号
    const currentTitleData = userTitles.value.find(title => title.isCurrent)
    currentTitle.value = currentTitleData?.title || ''
    
  } catch (err) {
    console.error('加载用户称号失败:', err)
  }
}

// 更换称号
const changeTitle = async (newTitle) => {
  try {
    changingTitle.value = newTitle
    
    const result = await userLevelAPI.changeTitle({
      userId: props.userId,
      newTitle: newTitle
    })
    
    if (result.success !== false) {
      currentTitle.value = newTitle
      ElMessage.success('称号更换成功！')
      
      // 重新加载用户称号
      await loadUserTitles()
    } else {
      ElMessage.error(result.message || '称号更换失败')
    }
    
  } catch (err) {
    console.error('更换称号失败:', err)
    ElMessage.error('称号更换失败，请重试')
  } finally {
    changingTitle.value = ''
  }
}

// 初始化
onMounted(async () => {
  await Promise.all([
    loadAllTitles(),
    loadUserTitles()
  ])
})
</script>

<style scoped>
.user-titles-manager {
  max-width: 1000px;
  margin: 0 auto;
}

.current-title-section {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
}

.current-title-section h4 {
  margin: 0 0 12px 0;
  color: #0369a1;
  font-size: 16px;
}

.current-title-display {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-weight: 600;
  font-size: 14px;
}

.title-badge.current {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
}

.title-description {
  color: #64748b;
  font-size: 14px;
}

.all-titles-section {
  margin-bottom: 24px;
}

.all-titles-section h4 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 18px;
}

.loading, .error {
  text-align: center;
  padding: 40px;
  color: #6b7280;
}

.error {
  color: #ef4444;
}

.titles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.title-card {
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px;
  transition: all 0.3s ease;
}

.title-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.title-card.unlocked {
  border-color: #10b981;
  background: #f0fdf4;
}

.title-card.locked {
  border-color: #d1d5db;
  background: #f9fafb;
  opacity: 0.7;
}

.title-card.current {
  border-color: #3b82f6;
  background: #eff6ff;
}

.title-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.title-name {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
}

.title-status {
  display: flex;
  gap: 8px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 600;
  text-transform: uppercase;
}

.status-badge.current {
  background: #3b82f6;
  color: white;
}

.status-badge.unlocked {
  background: #10b981;
  color: white;
}

.status-badge.locked {
  background: #6b7280;
  color: white;
}

.title-info {
  margin-bottom: 16px;
}

.title-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #6b7280;
}

.title-description {
  color: #374151 !important;
  font-weight: 500;
}

.title-requirement {
  color: #d97706 !important;
}

.title-level {
  color: #7c3aed !important;
}

.title-actions {
  text-align: center;
}

.titles-stats {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #64748b;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.stat-value.unlocked {
  color: #10b981;
}

.stat-value.locked {
  color: #6b7280;
}

@media (max-width: 768px) {
  .titles-grid {
    grid-template-columns: 1fr;
  }
  
  .titles-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
